/*
 * File:    CRC.c
 * Project:	HobbyPilotFirmware (HPF)
 * Author:  Wouter van Verre
 *
 * Created on February 20, 2011, 5:17 PM
 */

#include "Header.h"

/**
*
* CALCULATE THE CHECKSUM
*
*/

/**
* @brief Initiliaze the buffer for the X.25 CRC
*
* @param crcAccum the 16 bit X.25 CRC
*/
void crc_init(uint16* crcAccum)
{
        *crcAccum = X25_INIT_CRC;
}

/**
* @brief Accumulate the X.25 CRC by adding one char at a time.
*
* The checksum function adds the hash of one char at a time to the
* 16 bit checksum (uint16_t).
*
* @param data new char to hash
* @param crcAccum the already accumulated checksum
**/
void crc_accumulate(uint8 data, uint16 *crcAccum)
{
        /*Accumulate one byte of data into the CRC*/
        uint8 tmp;

        tmp= data ^ (uint8)(*crcAccum &0xff);
        tmp^= (tmp<<4);
        *crcAccum = (*crcAccum>>8) ^ (tmp<<8) ^ (tmp <<3) ^ (tmp>>4);
}

/**
* @brief Calculates the X.25 checksum on a byte buffer
*
* @param pBuffer buffer containing the byte array to hash
* @param length length of the byte array
* @return the checksum over the buffer bytes
**/
void crc_calculate(uint8* pBuffer, int length, uint16* pChecksum)
{

        // For a "message" of length bytes contained in the unsigned char array
        // pointed to by pBuffer, calculate the CRC
  
        uint8* pTmp;
		int i;

        pTmp=pBuffer;

        for (i = 0; i < length; i++){
                crc_accumulate(*pTmp++, pChecksum);
        }
}
